package com.cgc.venus.server.job.jobdetail;

import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.job.Constants;
import com.cgc.venus.server.job.bean.AppManageBean;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计空间应用
 */
public class StatsNamespaceAppJob extends StatsAppBaseJob {
    private static Logger logger = LoggerFactory.getLogger(StatsNamespaceAppJob.class);
    public StatsNamespaceAppJob() {
    }
    public void execute(JobExecutionContext context)  
        throws JobExecutionException {
        logger.info("统计空间应用job start...");
        List objs = new ArrayList<Object>();
        String sql="";
        String id=null;
        try {
            //查询统计值
            List<AppManageBean> qr=queryAllAppInfo();
            Map<String, List<AppManageBean>> map = qr.stream().collect(Collectors.groupingBy(AppManageBean::getNamespace));//根据命名空间进行分组查询
            for (String key : map.keySet()) {
                qr=map.get(key);
                int app_count_all=qr.size();
                int app_count_running=qr.stream().filter(ts -> StatsAppBaseJob.APP_STATUS_RUNNING.equals(ts.getStatus())).collect(Collectors.toList()).size();
                int app_count_close=qr.stream().filter(ts -> StatsAppBaseJob.APP_STATUS_CLOSE.equals(ts.getStatus())).collect(Collectors.toList()).size();
                List<AppManageBean> qrEx=qr.stream().filter(ts -> StatsAppBaseJob.APP_STATUS_ERROR.equals(ts.getStatus())).collect(Collectors.toList());
                int app_count_ex=qrEx.size();
                int app_count_today=qr.stream().filter(ts -> ts.isToday()).collect(Collectors.toList()).size();
                //处理告警
                if(app_count_ex>0){
                    //往告警表插入一条记录
                    String appExInfo="";
                    for(AppManageBean amb:qrEx){
                        if(appExInfo.equals("")){
                            appExInfo+=amb.getAppName();
                        }else{
                            appExInfo+=","+amb.getAppName();
                        }
                    }
                    String alertMsg="有"+app_count_ex+"个异常应用!,异常名称为:("+appExInfo+")";
                    handleEx(alertMsg,Constants.ALARM_TYPE_NS_APP,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,key);
                }
                //更新统计值表
                sql="select id from t_job_stats_namespace_app where date_format(create_time,'%Y-%m-%d')=date_format(NOW(),'%Y-%m-%d') and ns_name='"+key+"'";
                List<Map<String, Object>> l=getJdbcTemplate().queryForList(sql);
                if(l!=null&&l.size()>0){
                    //db update
                    id=l.get(0).get("id").toString();
                    sql = "update t_job_stats_namespace_app  set Ns_app_count_all=?,Ns_app_count_running=?,Ns_app_count_close=?,Ns_app_count_ex=?,Ns_app_count_today=?,last_update_time=NOW() where id=? and ns_name=?";
                }else{
                    //db insert
                    id = StringUtil.getUUID();
                    sql = "INSERT INTO t_job_stats_namespace_app(Ns_app_count_all,Ns_app_count_running,Ns_app_count_close,Ns_app_count_ex,Ns_app_count_today,id,ns_name,create_time,last_update_time) VALUES (?,?,?,?,?,?,?,NOW(),NOW())";
                }
                objs = new ArrayList<Object>();
                objs.add(app_count_all);
                objs.add(app_count_running);
                objs.add(app_count_close);
                objs.add(app_count_ex);
                objs.add(app_count_today);
                objs.add(id);
                objs.add(key);
                getJdbcTemplate().update(sql, objs.toArray());
            }
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            handleEx("统计空间应用任务异常,异常信息:"+getErrorInfoFromException(ex),Constants.ALARM_TYPE_JOB_ERROR,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,Constants.ALARM_NS_ALL);
            throw new JobExecutionException(ex);
        }
    }  
}